package Threads.AQS.diylock;

import Threads.Utils.log;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

//自定义实现一个不可重入锁
public class Mylock implements Lock {

    //自定义同步器
    final static class MySync extends AbstractQueuedSynchronizer{

        //attemp to get the lcok
        @Override
        protected boolean tryAcquire(int arg) {
            if (arg==1){
                if (compareAndSetState(0,1)){
                    setExclusiveOwnerThread(Thread.currentThread());
                    return true;
                }
            }
            return false;
        }

        //attempt to release the lock
        @Override
        protected boolean tryRelease(int arg) {
            if (arg==1){
                if (getState()==0)
                    throw new IllegalMonitorStateException();
                setExclusiveOwnerThread(null);
                setState(0);
                return true;
            }
            return false;
        }

        @Override
        protected boolean isHeldExclusively() {
            return getState()==1;
        }

        public Condition newCondition(){
            return sync.newCondition();
        }

    }


    //使用同步器，去构建一个锁
    static MySync sync=new MySync();

    @Override
    public void lock() {
        sync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1,unit.toNanos(time));
    }

    @Override
    public void unlock() {
        sync.release(1);
    }

    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }

    //test
    public static void main(String[] args) {
        test2();
    }

    //测试锁功能
    public static void test1(){
        Mylock mylock=new Mylock();
        new Thread(()->{
            mylock.lock();
            try {
                log.debug("locking--");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                log.debug("unlock");
                mylock.unlock();
            }
        },"t1").start();
        new Thread(()->{
            mylock.lock();
            try {
                log.debug("locking--");
            }finally {
                log.debug("unlock");
                mylock.unlock();
            }
        },"t2").start();
    }

    //测试不可重入
    //只会打印一次，代表在第二次lock的时候阻塞了
    //所以这个锁是不可重入的
    public static void test2(){
        Mylock lock=new Mylock();
        lock.lock();
        log.debug("locking--");
        lock.lock();
        log.debug("locking--");
    }
}
